<template>
  <div>
    <div class="tab-wrap flex-row">
      <ul class="flex-row item">
        <li :class="{'cur':indexPage=='1'}" @click="indexPage ='1'">待指派{{orders.list1?orders.list1.length:'0'}}</li>
        <li :class="{'cur':indexPage=='2'}" @click="indexPage ='2'">配送中{{orders.list2?orders.list2.length:'0'}}</li>
        <li :class="{'cur':indexPage=='3'}" @click="indexPage ='3'" >
          <el-badge style='font-size: 15px' :value="orders.list3.length?orders.list3.length:''"
                    :max="99" class="num-int" >异常{{orders.list3.length== 0 ? 0:''}}
          </el-badge>
        </li>
        <li :class="{'cur':indexPage=='4'}" @click="indexPage ='4'">超时完成{{orders.list4?orders.list4.length:'0'}}</li>
      </ul>
      <div class="shop-state fle-ver">
        <div class="state flex-row">营业时间 <span>运营中</span></div>
        <div class="time">{{orders.agentbusiness.firstTime|cationTime(orders.agentbusiness.secondTime)}}</div>
      </div>
    </div>
    <div class="bg-empty"></div>
    <div class="tab1 padding-top" v-show="indexPage == '1'">
      <div class="p-left">
        <div class="flex head">
          <div class="shopers">当前骑手：
            <span class="shop" v-if="Object.keys(curShoperMsg).length > 0">
              <span class="name">{{curShoperMsg.name}}</span>
              <span class="data">(<em>{{curShoperMsg.jieDanNum}}/</em><em>{{curShoperMsg.peiSongNum}}/</em>{{curShoperMsg.totalNum}})</span>
            </span>
            <span v-else>暂未选择骑手</span>
          </div>
          <el-button type="primary" plain icon="el-icon-refresh" @click="resall()"></el-button>
        </div>
        <div class="order">
          <ul class="o-list" id="order-list">
            <li v-for="(item) in orders.list1"
                :draggable="!item.suportself && item.isdeliver != '1' && !item.shopperid"
                @dragstart="dragOrders($event,item)"
                :key="item.id"
                :class="{'cur':curlistOrder.ids.indexOf(item.id)>=0}"
                @click="orderLine(item)">
              <div class="flex c-dui row">
                <div class="flex">
                  <span class="get flex-row-ver">取</span>
                  <span class="mat shop">{{item.businessname}}</span>
                  <span class="index">#{{item.ordernumber}}</span>
                </div>
                <span class="dui el-icon-circle-check"></span>
              </div>
              <div class="flex row" v-if='item.suportself'>
                <span class="shou flex-row-ver">自</span>
                <span class="mat">用户自取</span>
              </div>
              <div class="flex row" v-else>
                <span class="shou flex-row-ver">送</span>
                <span class="mat">{{item.useraddress}}</span>
              </div>
              <div class="flex row" style="margin-left:30px;">
                <span><time-out :endTime='item.distime'></time-out>/</span>
                <span class="adjust-t"><adjust-out :endTime='item.createtime'></adjust-out></span>
              </div>
              <div class="flex row" style="margin-left:30px;">
                <span v-if="item.status < '2' " class="tip">商家未接单</span>
                <span class="tip2" v-else>商家已接单</span>
                <span v-if='item.suportself' class="tip2">用户自取</span>
                <span v-else>
                  <span v-if='item.isdeliver =="1"' class="tip2">商家自配送</span>
                  <span v-else>
                    <span v-if="item.shopperid" class="tip2">,骑手已接单</span><span class="tip" v-else>,骑手未接单</span>
                  </span>
                </span>
                <span class="tip">,请及时处理</span>
              </div>
            </li>
          </ul>
          <div class="butns">
            <el-tooltip :content="orderBtns.orders.content" placement="top" :disabled="!orderBtns.orders.notSet">
              <el-button v-if="!orderBtns.orders.notSet"   style="margin: 0 0 3px 0" type="success"  plain size="mini" @click="orderReceivingOrFromASingle(1)">接单</el-button>
              <el-button class="is-disabled" v-else  style="margin: 0 0 3px 0" type="success"  plain size="mini">接单</el-button>
            </el-tooltip>
            <el-tooltip :content="orderBtns.rejection.content" placement="top" :disabled="!orderBtns.rejection.notSet">
              <el-button v-if="!orderBtns.rejection.notSet" style="margin: 0" type="danger" plain size="mini" @click="orderReceivingOrFromASingle(2)">拒单</el-button>
              <el-button class="is-disabled" v-else style="margin: 0" type="danger" plain size="mini" >拒单</el-button>
            </el-tooltip>
            <el-tooltip :content="orderBtns.passOrder.content" placement="top" :disabled="!orderBtns.passOrder.notSet">
              <el-button v-if="!orderBtns.passOrder.notSet" style="margin: 0" type="success" plain size="mini" @click="confirmToSendASingle()">派单</el-button>
              <el-button class="is-disabled" v-else  style="margin: 0" type="success" plain size="mini" >派单</el-button>
            </el-tooltip>
            <el-tooltip :content="orderBtns.cancel.content" placement="top" :disabled="!orderBtns.cancel.notSet">
              <el-button v-if="!orderBtns.cancel.notSet" style="margin: 0" type="danger" plain size="mini" @click="hnadOrderCancel()">取消</el-button>
              <el-button class="is-disabled" v-else style="margin: 0" type="danger" plain size="mini" >取消</el-button>
            </el-tooltip>
          </div>
        </div>
      </div>
      <div class="p-right">
        <div class="flex head">
          <!--<el-input placeholder="搜骑手,为空查询全部" v-model="name" class="input-with-select">
              <el-button slot="append" icon="el-icon-search" ></el-button>
          </el-input>-->
        </div>
        <div class="o-btns flex-row-ver">
          <span :class="{'cur':type==1}" @click="switchTheRider(1)">开工<br/>{{shopworkList.workingNum}}</span>
          <span :class="{'cur':type==2}" @click="switchTheRider(2)">下班<br/>{{shopworkList.noWorkingNum}}</span>
        </div>
        <ul class="ul-s" v-if="type ==1" id="shopper-list" style="position: relative" >
          <li class="flex-ver" v-for="item in shopworkList.workingList"
              :key="item.id" :class="{'cur':curlistShoper==item.id}"
              @drop="orderDrop($event,item)"
              @dragover="allowDrop($event)"
              @click="curhandShoper(item)"
              style="cursor: pointer">
            <div class="flex-row row">
              <span class="name">{{item.name}}</span>
              <span class="data"><em>{{item.jieDanNum}}/</em><em>{{item.peiSongNum}}/</em>{{item.totalNum}}</span>
            </div>
            <div class="tel">{{item.munber}}</div>
          </li>
        </ul>
        <ul class="ul-s" v-if="type ==2" style="background: #f1f1f1">
          <li class="flex-ver" v-for="item in  shopworkList.noWorkingList" :key="item.id">
            <div class="flex-row row">
              <span class="name">{{item.name}}</span>
              <span class="data"><em>{{item.jieDanNum}}/</em><em>{{item.peiSongNum}}/</em>{{item.totalNum}}</span>
            </div>
            <div class="tel">{{item.munber}}</div>
          </li>
        </ul>
      </div>
      <div id="container" class="adjust-location base-diy-map"></div>
    </div>
    <div class="tab2 padding-top" v-show="indexPage == '2'">
      <div class="base-table-wrap">
        <el-row class="item-sub" type="flex">
          <span :class="{'cur':statu =='1'}" @click="changeStatus('1')">全部{{orders.list2?orders.list2.length:'0'}}</span>
          <span :class="{'cur':statu =='2'}" @click="changeStatus('2')">前往商家{{orders.list5?orders.list5.length:'0'}}</span>
          <span :class="{'cur':statu =='3'}" @click="changeStatus('3')">待取餐{{orders.list6?orders.list6.length:'0'}}</span>
          <span :class="{'cur':statu =='4'}" @click="changeStatus('4')">待送达{{orders.list7?orders.list7.length:'0'}}</span>
        </el-row>
        <el-table :data="statuOrder" style="width: 100%"
                  :default-sort="{prop: 'date', order: 'descending'}">
          <el-table-column label="商户全部" min-width="160px" align="left">
            <template slot-scope="scope">
              <div style="font-weight: 600;">{{scope.row.businessname}}</div>
              <div>{{scope.row.businessaddr}}</div>
            </template>
          </el-table-column>
          <el-table-column label="流水号" width="80px" align="left">
            <template slot-scope="scope">#{{scope.row.ordernumber}}</template>
          </el-table-column>
          <el-table-column prop="ordercode" label="订单号" min-width="150" align="center"></el-table-column>
          <el-table-column label="支付信息" min-width="80px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.totalpay}}</div>
              <div>{{scope.row.ispay == '1' ? paySatus(scope.row.paytype) : '未支付' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="订餐人" min-width="140px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.username}}|{{scope.row.usermobile}}</div>
              <div>{{scope.row.useraddress}}{{scope.row.address}}</div>
            </template>
          </el-table-column>
          <el-table-column label="骑手" min-width="140px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.shopper}}</div><div>{{scope.row.shoppermobile}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="distime" label="距超时" min-width="140px" align="left">
            <template slot-scope="scope">
              <yue-time-out :endTime='scope.row.distime'></yue-time-out>
            </template>
          </el-table-column>
          <el-table-column prop="acepttime" label="接单时间" min-width="140px" sortable align="left"></el-table-column>
          <el-table-column prop="statstr" label="状态" min-width="100px" align="left"></el-table-column>
          <el-table-column fixed="right" label="操作" width="180" align="center">
            <template slot-scope="scope">
              <el-button style="margin: 0 0 5px 0" type="warnning" size="mini"
                         @click="reassigningTheRider(scope.row.id,scope.row.shopperid)" round plain>订单改派
              </el-button>
              <el-dropdown>
                <el-button  type="danger" size="mini" round plain >更改状态</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-if='scope.row.status<="3"'>
                    <el-button type='text' @click="alterTheState(scope.row.id,4)">商品打包</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item v-if='scope.row.status<="4"' >
                    <el-button type='text' @click="alterTheState(scope.row.id,5)"> 商品配送</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item >
                    <el-button type='text' @click="alterTheState(scope.row.id,8)">订单完成</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item >
                    <el-button type='text' style="border-top: 1px solid" @click="setStateError(scope.row.id)">
                      <span style="color: red;">标记异常</span>
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item >
                    <el-button type='text' style="border-top: 1px solid" @click="hnadOrderCancel(scope.row.id)">
                      <span style="color: red;">取消订单</span>
                    </el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog title="选中骑手" v-dialogDrag :visible.sync="dialogTableVisible" width="600px">
        <div class="big-class">
          <el-radio-group v-model="radioShopper">
            <el-radio v-for="item in shopworkList.workingList" :key="item.id" :label="item.id">{{item.name}}
            </el-radio>
          </el-radio-group>
        </div>
        <div class="shop-save">
          <el-button @click="saveChangeShopper()" type="primary">保存</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="tab3 padding-top" v-show="indexPage == '3'">
      <div class="base-table-wrap">
        <el-table :data="orders.list3" style="width: 100%" :default-sort="{prop: 'date', order: 'descending'}">
          <el-table-column label="商户全部" min-width="120px" align="left">
            <template slot-scope="scope">
              <div style="font-weight: 600;">{{scope.row.businessname}}</div>
              <div>{{scope.row.businessaddr}}</div>
            </template>
          </el-table-column>
          <el-table-column label="流水号" min-width="80px" align="left">
            <template slot-scope="scope">#{{scope.row.ordernumber}}</template>
          </el-table-column>
          <el-table-column prop="ordercode" label="订单号" min-width="140" align="center"></el-table-column>
          <el-table-column label="支付信息" min-width="80px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.totalpay}}</div>
              <div>{{scope.row.ispay == '1' ? paySatus(scope.row.paytype) : '未支付' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="订餐人" min-width="140px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.username}}|{{scope.row.usermobile}}</div>
              <div>{{scope.row.useraddress}}{{scope.row.address }}</div>
            </template>
          </el-table-column>
          <el-table-column label="骑手" min-width="140px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.shopper}}</div>
              <div>{{scope.row.shoppermobile}}</div>
            </template>
          </el-table-column>
          <el-table-column  label="异常原因" min-width="120px" align="left">
            <template slot-scope="scope">
              {{scope.row.abnormalcontext}}
            </template>
          </el-table-column>
          <el-table-column prop="acepttime" label="接单时间" min-width="140px" sortable align="left"></el-table-column>
          <el-table-column prop="statstr" label="状态" min-width="100px" align="left"></el-table-column>

          <!--11.19增加操作 取消 退款-->
          <el-table-column fixed="right" label="操作" width="180px" align="center">
            <template slot-scope="scope">
              <el-button v-if="scope.row.iscancel !== 1 && scope.row.isrefund !== 1" style="color: #29c734;"
                         @click="cancelAbnormal(scope.row.id)" class="refund"
                         type="text">取消标记异常</el-button>
              <el-button v-if="scope.row.iscancel === 1"
                         style="color: #29c734;"
                         @click="orderCancel(scope.row.id, 2)" class="refund"
                         type="text">同意取消</el-button>
              <el-button v-if="scope.row.iscancel === 1"
                         @click="orderCancel(scope.row.id, 3)" class="refund"
                         type="text">驳回取消</el-button>
              <el-button v-if="scope.row.isrefund === 1"
                         style="color: #29c734;"
                         @click="orderRefund(scope.row.id, 1)" class="refund"
                         type="text">同意退款</el-button>
              <el-button v-if="scope.row.isrefund === 1"
                         @click="orderRefund(scope.row.id, 0)" class="refund"
                         type="text" >驳回退款</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="tab4 padding-top" v-show="indexPage == '4'">
      <div class="base-table-wrap">
        <el-table :data="orders.list4" style="width: 100%" :default-sort="{prop: 'date', order: 'descending'}">
          <el-table-column label="商户全部" min-width="120px" align="left">
            <template slot-scope="scope">
              <div style="font-weight: 600;">{{scope.row.businessname}}</div>
              <div>{{scope.row.businessaddr}}</div>
            </template>
          </el-table-column>
          <el-table-column label="流水号" min-width="80px" align="left">
            <template slot-scope="scope">#{{scope.row.ordernumber}}</template>
          </el-table-column>
          <el-table-column prop="ordercode" label="订单号" min-width="140" align="center"></el-table-column>
          <el-table-column label="支付信息" min-width="80px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.totalpay}}</div>
              <div>{{scope.row.ispay == '1' ?paySatus(scope.row.paytype) : '未支付' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="订餐人" min-width="140px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.username}}|{{scope.row.usermobile}}</div>
              <div>{{scope.row.useraddress}}{{scope.row.address }}</div>
            </template>
          </el-table-column>
          <el-table-column label="骑手" min-width="140px" align="left">
            <template slot-scope="scope">
              <div>{{scope.row.shopper}}</div>
              <div>{{scope.row.shoppermobile}}</div>
            </template>
          </el-table-column>
          <el-table-column  label="超时时长"  min-width="120px" align="left">
            <template slot-scope="scope">
              <span v-html='$options.filters.capitalize(scope.row.distime,scope.row.readytime)'></span>
            </template>
          </el-table-column>
          <el-table-column prop="acepttime" label="接单时间" min-width="140px" sortable align="left"></el-table-column>
          <el-table-column prop="statstr" label="状态" min-width="100px" align="left"></el-table-column>
        </el-table>
      </div>
    </div>
    <div class="listen" >
      <audio id="appleline"><source :src="appleline"/> </audio>
    </div>
  </div>
</template>

<script>
  import yueTimeOut from './yueTimeOut'
  import timeOut from './timeOut'
  import adjustOut from './adjustOut'
  import applelines from '@/assets/video/appleline.mp3'
  import { paySatus } from '@/utils/ptkc'
  import adjust1 from '../mixins/adjust1'
  import websocketPath from '@/utils/websocketPath'
  import { orderSchedulingList, findShopper } from '@/api/adjust'
  export default {
    mixins: [adjust1],
    components: { timeOut, adjustOut, yueTimeOut },
    props: {
      videoSet: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        paySatus: paySatus,
        orderType: '',                                 //抢单或派单
        assignType: '1',                               //正在指派或待指派
        curlistOrder: {ids: [], order: [], markers: []}, //当前选择的正在指派订单id 和地图标记
        shopName: '',                                  //搜索骑手名称关键子
        type: 1,                                       //骑手上班或下班切换
        shopworkList: {},                              //骑手
        curlistShoper: '',                             //当前被点击的起手
        openShopOrder: null,                           //当前仅仅显示这个起手的信息和收取
        openShopOrderList: [],                         //当前仅仅显示这个起手下的所有订单
        shoperMarkers: {ids: [], markers: []},         //骑手标记
        //配送中
        dialogTableVisible: false,                      //弹出层
        radioShopper: '',                               //选中的骑手
        curShopper: '',                                 //当前骑手
        radioOrderId: '',                               //选中的订单
        statu: '1',                                     //订单状态
        statuOrder: [], // 选中的状态的数据
        emptyText: '',                                  //表格请求提示
        newPage: 1,                                     //默认
        orders: {                                       //订单所有数据
          agentbusiness: {},
          list1: [],
          list2: [],
          list3: [],
          list4: [],
          list5: [],
          list6: [],
          list7: [],
        },
        orderBtns: { // 订单操作按钮
          orders: { notSet: true, content: '未选择订单'},
          rejection: { notSet: true, content: '未选择订单'},
          passOrder: { notSet: true, content: '未选择订单'},
          cancel: { notSet: true, content: '未选择订单'}
        },
        indexPage: '1', //indexPage
        curShoperMsg: {},  // 当前选中的骑手
        isRefund:false,   //驳回退款弹窗
        isCancel: false, // 驳回取消弹窗
        formCancel:{
          id: '',
          remarks: ''  // 驳回取消原因
        },
        formRefund:{
          id: '',
          remarks: ''  // 驳回退款原因
        },
        neworder: null, // 订单语言

        lockReconnect: false, // websocke 防重复
        timeoutObj: null, // 服务器未相应倒计时
        reastWebsocket: null, // 重启websocket倒计时
        ws: null, // websocket 对象
        stopWebSocket: false, // 页面关闭
        restOrderTime: null, // 重启接口倒计时
        appleline: applelines // 语音文件
      }
    },
    filters: {
      filterShoper(obj) {
        if (Object.keys(obj).length > 0) {
          return `<span class="name">${obj.name}</span><span class="data">(<em>${obj.jieDanNum}/</em><em>${obj.peiSongNum}/</em>${obj.totalNum})</span>`
        } else {
          return '当前未选择骑手'
        }
      },
      cationTime(t1, t2) {
        let str = '', ts1 = t1, ts2 = t2
        if (ts1) str += ts1.replace(/,/g, "-")
        if (ts2) str += ',' + ts2.replace(/,/g, "-")
        return str
      },
      capitalize(time, readytime) {
        let times = time
        let readytimes = readytime
        if (times && readytimes) {
          let endTime = new Date(times.replace(/-/g, "/")).getTime()
          let nowTime = new Date(readytimes.replace(/-/g, "/")).getTime()
          let time = Math.ceil((nowTime - endTime) / 1000 / 60)
          if (time >= '60') {
            let h = Math.floor(time / 60)
            let m = time % 60 == 0 ? '' : `${time % 60}分`
            return `<span style='color:red;'>超时${h}小时${m}</span>`
          } else {
            if(time<10) return `超时${time}分`
            else return `<span style='color:red;'>超时${time}分</span>`
          }
        } else {
          return `未知`
        }
      },
    },
    watch:{
      'orders.list1':{
        handler(val,oldval){
          this.$emit('wmWebsockerNum',this.orders.list1.length)
        },
        deep:true
      },
      'curlistOrder.order': { // 监听选取的订单控制可操作按钮
        handler(val,oldval) {
          if (val.length > 0) {
            const arr = []
            let shoperSet = false
            let orderSet = false
            val.forEach((item) => {
              if (item.suportself || item.shopperid || item.isdeliver =="1") {
                this.orderBtns.passOrder.notSet = true
                if (item.suportself && arr.indexOf('自取单') === -1){
                  arr.push('自取单')
                }
                if (item.shopperid  && arr.indexOf('已派单') === -1){
                  arr.push('已派单')
                }
                if (item.isdeliver == '1'  && arr.indexOf('自配送单') === -1){
                  arr.push('自配送单')
                }
                shoperSet = true
              }
              if (item.status >= 2) {
                orderSet = true
              }
            })
            this.orderBtns = {
              orders: { notSet: orderSet, content: '含有已接单'},
              rejection: { notSet: orderSet, content: '含有已接单'},
              passOrder: { notSet: shoperSet, content: '含有'+ arr.join('、')},
              cancel: {
                notSet: !(val.length === 1 && val[0].status >= 2),
                content: val.length === 1 && val[0].status <= 2 ? '商家未接单' : '取消只支持单个订单操作'
              }
            }
          } else {
            this.orderBtns = {
              orders: { notSet: true, content: '未选择订单'},
              rejection: { notSet: true, content: '未选择订单'},
              passOrder: { notSet: true, content: '未选择订单'},
              cancel: { notSet: true, content: '未选择订单'}
            }
          }
        }
      }
    },
    methods: {
      switchTheRider(int) {  //本地切换上下班骑手
        this.type = int
      },
      dragOrders(ev,item) { // 拖拽开始
        ev.dataTransfer.setData("Te",JSON.stringify(item));
      },
      orderDrop(ev,item) { // 拖拽释放
        ev.preventDefault();
        var data=ev.dataTransfer.getData("Te");
        this.$confirm(`是否指派给${item.name}？`, '拖动派单提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'success',
          center: true
        }).then(() => {
        this.confirmToSendASingle(JSON.parse(data).id,item.id)
        }).catch(() => {
          this.$message.info('已取消派单操作')
        })
      },
      allowDrop(ev) { // 拖拽
        ev.preventDefault();
      },
      confirmToSendASingle(orderId,shoperId) { //指派订单
        if (!shoperId && this.curlistShoper === '') {
          this.$message.error('您未选择骑手')
          return false
        }
        const params = {ids:orderId ? [orderId]: this.curlistOrder.ids, shopperid: shoperId ? shoperId : this.curlistShoper}
        this.$http.post('/server/order/setRiderOrder', JSON.stringify(params)).then(res => {
          if (res.data.success) {
            this.$message({type: 'success', message: '派单成功'})
          }
        })
      },
      hnadOrderCancel(params) { // 批量取消订单
        const id =params ?params : this.curlistOrder.ids.join(',')
        this.$confirm(`是否确认取消订单？`, '取消订单提示！', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'success',
          center: true
        }).then(() => {
          this.suerCancel(id, 2, '', true)
        }).catch(() => {
          this.$message.info('已取消取消订单操作')
        })
      },
      orderCancel(id, type) { // 取消订单确认框
        if (type === 2) {
          this.$confirm(`是否同意取消当前订单？`, '取消订单提示！', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'success',
            center: true
          }).then(() => {
            this.suerCancel(id, type)
          }).catch(() => {
            this.$message.info('已取消取消订单操作')
          })
        } else {
          this.$prompt('请输入驳回原因', '驳回用户取消订单！', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /^[\S\n\s]{0,20}$/,
            inputErrorMessage: '最多输入20个字符'
          }).then(({ value }) => {
            this.suerCancel(id, 3, value)
          }).catch(() => {
            this.$message({ type: 'info', message: '取消输入' })
          })
        }
      },
      suerCancel(id, type, value, isNew) { // 同意 、 不同意取消订单处理
        var eva = new FormData()
        eva.append('id', id ? id : this.formCancel.id)
        eva.append('remarks', type === 3 ? value : '')
        eva.append('isCancel', type ? type : 2)
        this.$http.post('/server/order/cancel_order', eva).then(res => {
          if (res.data.success) {
            this.$message({type: 'success', message: '订单取消成功'})
          }
        })
      },
      orderRefund(id, type) { // 同意退款确认框
        if (type === 1) {
          this.$confirm(`是否同意退款？`, '订单退款提示！', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'success',
            center: true
          }).then(() => {
            this.suerRefund(id, type)
          }).catch(() => {
            this.$message.info('已取消订单退款操作')
          })
        } else {
          this.$prompt('请输入驳回退款原因', '驳回退款！', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /^[\S\n\s]{0,20}$/,
            inputErrorMessage: '最多输入20个字符'
          }).then(({ value }) => {
            this.suerRefund(id, type, value)
          }).catch(() => {})
        }
      },
      suerRefund(id, type, value) { // 同意 、 不同意退款
        var eva = new FormData()
        eva.append('id', id)
        eva.append('remarks', type === 0 ? value : '')
        eva.append('confirm', type)
        this.$http.post('/server/order/refund', eva).then(res => {
          if (res.data.success) {
            if (this.isRefund) this.isRefund = false
            this.$message({type: 'success', message: '订单退款成功'})
          }
        }).catch(() => {
          if (isNew) loading.close()
        })
      },
      setStateError(id) { // 标记异常
        this.$prompt('请输入异常原因', '标记订单异常！', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[\S\n\s]{1,20}$/,
          inputErrorMessage: '异常原因未填或超出20个字符'
        }).then(({ value }) => {
          const params = { id, abnormalContext: value }
          this.$http.get('/server/order/setAbnormal?'+this.qs.stringify(params)).then(res => {
            if (res.data.success){
              this.$message.success('标记成功！')
            }
          })
        }).catch(() => {})
      },
      cancelAbnormal(id) { // 取消标记异常
        this.$http.get('/server/order/cancelAbnormal?'+ this.qs.stringify({id })).then(res => {
          if (res.data.success){
            this.$message.success('取消标记异常！')
          }
        })
      },
      orderReceivingOrFromASingle(type) { //据单抢单按钮
        const loading = this.$loading({
          lock: true,
          text: '更新订单...',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.3)',
          target: document.querySelector('#order-list')
        })
        let params = {ids: this.curlistOrder.ids, statusType: type}
        this.$http.post('/server/order/setRecordStatus', JSON.stringify(params)).then(res => {
          loading.close()
          if (res.data.success) {
            this.$message({type: 'success', message: '调度成功'})
          }
        }).catch(() => { loading.close() })
      },
      toObtainARider() { // 获取骑手
        const loading = this.$loading({
          lock: true,
          text: '获取骑手中...',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.3)',
          target: document.querySelector('#shopper-list')
        })
        const params = {name: this.name }
        findShopper(params).then(res => {
          if (res.success) {
            this.shopworkList = res.data
            this.showShoper()
          }
        }).finally(() => { loading.close() })
      },
      createWebSocket() { // 创建websocket
        try {
          const loginMsg = sessionStorage.getItem('loginMsg') || '{}'
          const p  = JSON.parse(loginMsg)
          if ('WebSocket' in window) {
            this.ws = new WebSocket(websocketPath() + '/websocket/diaodu/' + p.user + '/' + p.type + '/' + p.token)
          } else if ('MozWebSocket' in window) {
            this.ws = new WebSocket(websocketPath() + '/websocket/diaodu/' + p.user + '/' + p.type + '/' + p.token)
          } else {
            this.$alert("您的浏览器不支持websocket协议,建议使用新版谷歌、火狐等浏览器，请勿使用IE10以下浏览器，360浏览器请使用极速模式，不要使用兼容模式！")
            return false
          }
          this.websocket()
        } catch(e) {
          this.reconnect()
        }     
      },
      reconnect() { // websocket 重新链接
        if (!this.stopWebSocket) {
          if(this.lockReconnect) return
          this.lockReconnect = true
          this.reastWebsocket = setTimeout(() => { //没连接上会一直重连，设置延迟避免请求过多
            this.resall()
            this.lockReconnect = false
          }, 2000)
        }
      },
      websocket() {
        this.ws.onclose = () => {
          if (!this.stopWebSocket) {
            this.reconnect()
            console.log("外卖连接关闭, 开始重连"+new Date().toUTCString())
          } else {
            console.log('外卖-页面离开，不再重连'+new Date().toUTCString())
          }
        }
        this.ws.onerror = () => {
          this.reconnect()
          console.log('外卖连接错误, 开始重连!'+new Date().toUTCString())
        }
        this.ws.onopen = () => {
          this.heartCheck() // 心跳检测重置
          console.log('外卖连接成功!'+new Date().toUTCString())
        }
        this.ws.onmessage = evt => {
          this.heartCheck() // 心跳检测重置
          if (evt.data.indexOf('helle word') === -1) {
            const data = JSON.parse(evt.data)
            if (data.order) {
              this.wsOrder(data.order)
              this.wsInbution(data.order)
              this.wsIunusual(data.order)
              this.wsTimeout(data.order)
              if(data.order.status=='1'){
                if(this.videoSet && this.neworder){
                  try {
                    this.neworder.play()
                  }
                  catch(Exception) {
                    this.$alert('根据浏览器安全策略，需用户交互后才可以语言播报，请点击下方确认按钮！即交互！')
                  }
                }
              }
            }
            if (data.shopper) this.wsShoper(data.shopper)
          }
        }
      },
      heartCheck() { // 心跳
        clearTimeout(this.timeoutObj)
        this.timeoutObj = null
        this.timeoutObj = setTimeout(() =>{
          if (this.ws.readyState === 1) {
            this.ws.send('helle word')
          } else {
            console.log('外卖链接后台关闭，尝试重新链接'+new Date().toUTCString())
            this.reconnect()
          }
        }, 60000)
      },
      getOrderScheduling() { // 获取订单
        const loading = this.$loading({
          lock: true,
          text: '获取订单中...',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.3)',
          target: document.querySelector('#order-list')
        })
        orderSchedulingList().then(res => {
          if (res.success) {
            this.orders = res.data
            this.orders.list5 = []
            this.orders.list6 = []
            this.orders.list7 = []
            //this.$emit('orderType',this.orders.agentbusiness.orderMode == '2' ? '2' : '1')
            if (res.data.list2.length > 0) {
              res.data.list2.forEach(item => {
                if ((item.status === 3 || item.status === 4)&& item.shoppersign !== 1) this.orders.list5.push(item)
                else if ((item.status === 3||item.status == 4)&& item.shoppersign=== 1) this.orders.list6.push(item)
                else if (item.status === 5) this.orders.list7.push(item)
              })
            }
            this.statuOrder = this.orders.list2
            this.createWebSocket()
          } else {
            console.log('外卖接口异常，页面已终止服务') 
          }
        }).catch(() => {
          this.$notify({
            title: '网络异常！',
            message: '外卖订单获取失败，60s后尝试自动重新请求！',
            duration: 60000
          })
          console.log('网络异常，60秒后重新调用外卖订单接口')
          this.restOrderTime = setTimeout(() => {
            this.resall()
          }, 60000)
        }).finally(() => {
          loading.close()
        })
      },
      changeStatus(type) { // 切换状态
        this.statu = type
        if (type == '1') this.statuOrder = this.orders.list2
        else if (type == '2') this.statuOrder = this.orders.list5
        else if (type == '3') this.statuOrder = this.orders.list6
        else if (type == '4') this.statuOrder = this.orders.list7
      },
      wsInbution(val) {
        const index1 = this.orders.list2.findIndex(item => item.id === val.id)
        const index2 = this.orders.list5.findIndex(item => item.id === val.id)
        const index3 = this.orders.list6.findIndex(item => item.id === val.id)
        const index4 = this.orders.list7.findIndex(item => item.id === val.id)
        if (index1 > -1) {  //全部里显示与隐藏
          if (val.abnormal === 1) this.orders.list2.splice(index1, 1)
          else {
            if (val.status > 5 || val.status < 3) this.orders.list2.splice(index1, 1)
            else this.orders.list2.splice(index1, 1, val)
          }
        } else {
          if (val.abnormal !== 1) { } 
          else {
            if (val.status >= 3 && val.status <= 5) this.orders.list2.push(val)
          }
        }
        //找到了必是删除
        if (index2 > -1) this.orders.list5.splice(index2, 1)  //前往商家
        if (index3 > -1) this.orders.list6.splice(index3, 1) //待取货
        if (index4 > -1) this.orders.list7.splice(index4, 1) //待送达
        //对应插入增加
        if ((val.status === 3|| val.status === 4)&& val.shoppersign !== 1&& val.abnormal !== 1) this.orders.list5.push(val)
        if ((val.status === 3||val.status === 4)&& val.shoppersign === 1&& val.abnormal !== 1) this.orders.list6.push(val)
        if (val.status === 5 && val.abnormal !== 1) this.orders.list7.push(val)
      },
      reassigningTheRider(orderid, shopperid) {  //订单改派
        this.radioOrderId = orderid
        this.curShopper = shopperid
        this.dialogTableVisible = true
      },
      saveChangeShopper() {//订单改派
        const id = this.radioOrderId
        const shopperid = this.radioShopper
        if (id == this.curShopper) {
          this.$alert('骑手未发生变化！', '订单改派提示！')
          return false
        }
        const params = { id, shopperid }
        this.$http.get('/server/order/editOrderRider?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.dialogTableVisible = false
            this.$message.success('订单改派成功!')
          }
        })
      },
      alterTheState(orderid,type) { //修改状态
        const id = orderid,status = type
        this.$http.get('/server/order/editOrderStatus?' + this.qs.stringify({id,status})).then(res => {
          if ( res.data.success) {
            this.$message.success('修改状态成功!')
          }
        })
      },
      wsIunusual(val) {
        let cIndex = ''
        if (this.orders.list3.length > 0) cIndex = this.orders.list3.findIndex(item => item.id == val.id)
        if (cIndex >= -1) {
          if (val.abnormal == '1') this.$set(this.orders.list3, cIndex, val)
          else this.orders.list3.splice(cIndex, 1)
        } else {
          if (val.abnormal == '1') this.orders.list3.push(val)
        }
      },
      wsTimeout(val) {
        const endTime = new Date(val.distime.replace(/-/g, "/")).getTime()
        const nowTime = new Date().getTime()
        if (val.status == '8' && (endTime - nowTime) <= 0) this.orders.list4.push(val)
      },
      resall() {
        this.toObtainARider()
        this.getOrderScheduling()
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.neworder = document.getElementById('appleline')
      })
      this.resall()
    },
    destroyed() {
      this.stopWebSocket = true
      clearTimeout(this.reastWebsocket)
      clearTimeout(this.timeoutObj)
      if (this.restOrderTime) clearTimeout(this.restOrderTime)
      if (this.ws) this.ws.close()
    }
  }
</script>

<style lang="scss" scoped>
  @import '../css/header.css';
  @import '../css/adjust.scss';
  .big-class{
    padding: 15px;
    .el-radio{
      line-height: 30px;
    }
  }
  .shop-save{
    text-align: right;
  }
</style>
